
 <!DOCTYPE HTML>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  
    <title>RxJava基础篇(一) | RyanHuen</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="RyanHuen">
    

    
    <meta name="description" content="RxJava中有四个概念：
Observable：被观察者

Observer ：观察者

Subscribe：

订阅：

Observable和Observer通过subscribe()方法实现订阅关系，从而Observable可以在需要的时候发出事件来通知Observer(即被观察者通知观察者)




事件：由被观察者发出的东西。通常都是一个对象。



RxJava与传统观察者模式异同">
<meta property="og:type" content="article">
<meta property="og:title" content="RxJava基础篇(一)">
<meta property="og:url" content="http://www.ryanhuen.tech/2017/02/16/rx-serials-base-intro/index.html">
<meta property="og:site_name" content="RyanHuen">
<meta property="og:description" content="RxJava中有四个概念：
Observable：被观察者

Observer ：观察者

Subscribe：

订阅：

Observable和Observer通过subscribe()方法实现订阅关系，从而Observable可以在需要的时候发出事件来通知Observer(即被观察者通知观察者)




事件：由被观察者发出的东西。通常都是一个对象。



RxJava与传统观察者模式异同">
<meta property="og:image" content="http://olns0cxf5.bkt.clouddn.com/articleImages/rx/rx-base-1.jpg?watermark/2/text/Unlhbkh1ZW4\=/font/5b6u6L2v6ZuF6buR/fontsize/500/fill/I0JCQkJCQg\=\=/dissolve/100/gravity/SouthWest/dx/10/dy/10">
<meta property="og:updated_time" content="2017-02-22T02:57:18.666Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="RxJava基础篇(一)">
<meta name="twitter:description" content="RxJava中有四个概念：
Observable：被观察者

Observer ：观察者

Subscribe：

订阅：

Observable和Observer通过subscribe()方法实现订阅关系，从而Observable可以在需要的时候发出事件来通知Observer(即被观察者通知观察者)




事件：由被观察者发出的东西。通常都是一个对象。



RxJava与传统观察者模式异同">
<meta name="twitter:image" content="http://olns0cxf5.bkt.clouddn.com/articleImages/rx/rx-base-1.jpg?watermark/2/text/Unlhbkh1ZW4\=/font/5b6u6L2v6ZuF6buR/fontsize/500/fill/I0JCQkJCQg\=\=/dissolve/100/gravity/SouthWest/dx/10/dy/10">

    
    <link rel="alternative" href="/atom.xml" title="RyanHuen" type="application/atom+xml">
    
    
    <link rel="icon" href="/img/favicon.ico">
    
    
    <link rel="apple-touch-icon" href="/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/img/jacman.jpg">
    
    <link rel="stylesheet" href="/css/style.css">
</head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/"><img src="/img/logo.png" alt="RyanHuen" title="RyanHuen"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/" title="RyanHuen">RyanHuen</a></h1>
				<h2 class="blog-motto">I hope I can protect the one thing I can&#39;t live without.</h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="菜单">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/">首页</a></li>
					
						<li><a href="/archives">历程</a></li>
					
						<li><a href="/categories">分类</a></li>
					
						<li><a href="/tags">标签</a></li>
					
						<li><a href="/about">关于</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="搜索" />
						<input type="hidden" name="q" value="site:www.ryanhuen.tech">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/2017/02/16/rx-serials-base-intro/" title="RxJava基础篇(一)" itemprop="url">RxJava基础篇(一)</a>
  </h1>
  <p class="article-author">By
       
		<a href="/about" title="RyanHuen" target="_blank" itemprop="author">RyanHuen</a>
		
  <p class="article-time">
    <time datetime="2017-02-16T08:03:45.000Z" itemprop="datePublished"> 发表于 2017-02-16</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">文章目录</strong>
		
			<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#RxJava中有四个概念："><span class="toc-number">1.</span> <span class="toc-text">RxJava中有四个概念：</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#RxJava与传统观察者模式异同："><span class="toc-number">2.</span> <span class="toc-text">RxJava与传统观察者模式异同：</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Rx事件模型："><span class="toc-number">3.</span> <span class="toc-text">Rx事件模型：</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Rx事件模型图："><span class="toc-number">3.1.</span> <span class="toc-text">Rx事件模型图：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#首先了解几个概念："><span class="toc-number">3.2.</span> <span class="toc-text">首先了解几个概念：</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#基本使用："><span class="toc-number">4.</span> <span class="toc-text">基本使用：</span></a></li></ol>
		
		</div>
		
		<p><a id="org6bcab4f"></a></p>
<h1 id="RxJava中有四个概念："><a href="#RxJava中有四个概念：" class="headerlink" title="RxJava中有四个概念："></a>RxJava中有四个概念：</h1><ol>
<li><p>Observable：被观察者</p>
</li>
<li><p>Observer ：观察者</p>
</li>
<li><p>Subscribe：</p>
<ol>
<li><p>订阅：</p>
<ol>
<li>Observable和Observer通过subscribe()方法实现订阅关系，从而Observable可以在需要的时候发出事件来通知Observer(即被观察者通知观察者)</li>
</ol>
</li>
</ol>
</li>
<li><p>事件：由被观察者发出的东西。通常都是一个对象。</p>
</li>
</ol>
<p><a id="org268d805"></a></p>
<h1 id="RxJava与传统观察者模式异同："><a href="#RxJava与传统观察者模式异同：" class="headerlink" title="RxJava与传统观察者模式异同："></a>RxJava与传统观察者模式异同：</h1><ol>
<li><p>多了以下方法：</p>
<ol>
<li><p>onCompleted()：</p>
<ol>
<li>事件队列完结后执行的方法，也就是观察者与被观察者的联系结束以后回调的方法。</li>
</ol>
</li>
<li><p>onError(Throwable e)：事件队列异常的时候执行的方法,当联系发生问题是，进行回调的方法,通常会带上出错的异常信息</p>
</li>
<li><p>上述两个方法中总有一个会被回调，并且两者是互斥的(也就是只有其中一个能够被回调)。</p>
</li>
</ol>
</li>
</ol>
<p><a id="org32066d9"></a></p>
<h1 id="Rx事件模型："><a href="#Rx事件模型：" class="headerlink" title="Rx事件模型："></a>Rx事件模型：</h1><p><a id="orgbec85f8"></a></p>
<h2 id="Rx事件模型图："><a href="#Rx事件模型图：" class="headerlink" title="Rx事件模型图："></a>Rx事件模型图：</h2><blockquote>
<p><img src="http://olns0cxf5.bkt.clouddn.com/articleImages/rx/rx-base-1.jpg?watermark/2/text/Unlhbkh1ZW4\=/font/5b6u6L2v6ZuF6buR/fontsize/500/fill/I0JCQkJCQg\=\=/dissolve/100/gravity/SouthWest/dx/10/dy/10" alt="img"></p>
</blockquote>
<p><a id="org0da4ade"></a></p>
<h2 id="首先了解几个概念："><a href="#首先了解几个概念：" class="headerlink" title="首先了解几个概念："></a>首先了解几个概念：</h2><ol>
<li><p>RX事件流：</p>
<ol>
<li>首先RX的整个流程，我们可以看作是一条小河，河水从上游一直不断地往下游流去。</li>
</ol>
</li>
<li><p>上游：</p>
<ol>
<li>被观察者（Observable）</li>
</ol>
</li>
<li><p>下游：</p>
<ol>
<li>观察者（Observer）</li>
</ol>
</li>
<li><p>他们之间的联系：</p>
<ol>
<li><p>他们通过下述方法建立联系.</p>
<pre><code>subscribe()
</code></pre></li>
</ol>
</li>
<li><p>事件的传递：</p>
<ol>
<li>事件就是从上游(被观察者)发出，流到下游（观察者）处，下游（观察者）接收到事件后做出相应的响应的过程。</li>
</ol>
</li>
</ol>
<p><a id="org17d439d"></a></p>
<h1 id="基本使用："><a href="#基本使用：" class="headerlink" title="基本使用："></a>基本使用：</h1><ol>
<li><p>创建上游（被观察者：Observable）</p>
<ol>
<li><p>先看代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">Observable&lt;String&gt; observable = Observable.create(<span class="keyword">new</span> ObservableOnSubscribe&lt;String&gt;() &#123;</div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">subscribe</span><span class="params">(ObservableEmitter&lt;String&gt; e<span class="comment">/* 事件发射器 */</span>)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">            <span class="comment">// 发射事件</span></div><div class="line">            e.onNext(<span class="string">"事件1"</span>);</div><div class="line">            e.onNext(<span class="string">"事件2"</span>);</div><div class="line">            e.onNext(<span class="string">"事件3"</span>);</div><div class="line">            e.onComplete();</div><div class="line">        &#125;</div><div class="line">    &#125;);</div></pre></td></tr></table></figure>
</li>
<li><p>概念：</p>
<ol>
<li><p>事件发射器：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">ObservableEmitter    <span class="comment">//事件发射器</span></div></pre></td></tr></table></figure>
</li>
<li><p>顾名思义，事件发射器用于发射事件，可以发射以下三种类型的事件：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">onNext(T value)  <span class="comment">//正常地将某个事件发射出去（T：表示事件的类型）</span></div><div class="line">onComplete()   <span class="comment">//事件流结束后发射一个完成的消息</span></div><div class="line">onError(Throwable e)   <span class="comment">//事件流过程中出现错误发射异常信息</span></div><div class="line"><span class="comment">//显然后面两个方法是上游专门用来通知下游事件流是否成功的</span></div></pre></td></tr></table></figure>
</li>
</ol>
</li>
<li><p>事件发送规则：</p>
<ol>
<li><p>发射事件动作：</p>
<pre><code>onNext()
</code></pre><ol>
<li>可以被上游无限发送、也可以无限接收</li>
</ol>
</li>
<li><p>事件发射完成</p>
<pre><code>onComplete()：
</code></pre><ol>
<li><p>此动作之后，上游可以继续发送事件，但是下游在此之后，将不再继续接收事件</p>
</li>
<li><p>此动作进行多次不造成错误，下游只在第一次响应后不再响应。</p>
</li>
<li><p>上游可以不做此动作(也就是说上游完全可以不告诉下游事件流是否发送完毕)</p>
</li>
</ol>
</li>
<li><p>事件发射过程中出错</p>
<pre><code>onError()：
</code></pre><ol>
<li><p>此动作之后，上游可以继续发送事件，但是下游在此之后，讲不再鸡血接收事件。</p>
</li>
<li><p>此动作进行多次将造成错误，下游接收第二个onError会导致程序崩溃</p>
</li>
<li><p>上游可以不做此动作(也就是说上游完全可以不告诉下游事件流是否发送完毕)</p>
</li>
</ol>
</li>
</ol>
</li>
<li><p>多种创建方式</p>
<ol>
<li><p>单个创建：</p>
<pre><code>create()：
</code></pre><ol>
<li>上述代码已经阐述</li>
</ol>
</li>
<li><p>逐个发射:</p>
<pre><code>just()：
</code></pre><ol>
<li>将传入的参数依次发送出来：<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">Observable.just(<span class="string">"事件0"</span>, <span class="string">"事件1"</span>, <span class="string">"事件2"</span>, <span class="string">"事件3"</span>, <span class="string">"事件4"</span>, <span class="string">"事件5"</span>, <span class="string">"事件6"</span>, <span class="string">"事件7"</span>, <span class="string">"事件8"</span>, <span class="string">"事件9"</span>)</div><div class="line">    .subscribe();</div></pre></td></tr></table></figure>
</li>
</ol>
</li>
<li><p>迭代发射：</p>
<pre><code>fromIterable()：
</code></pre><ol>
<li>将传入的集合中的每一个元素迭代发射<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Observable.fromIterable(Iterable&lt;? extends T&gt; source)</div></pre></td></tr></table></figure>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
<li><p>创建下游（观察者：Observer）：</p>
<ol>
<li><p>先看代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">Observer&lt;String&gt; observer = <span class="keyword">new</span> Observer&lt;String&gt;() &#123;</div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onSubscribe</span><span class="params">(Disposable d)</span> </span>&#123;</div><div class="line">            Log.d(TAG, <span class="string">"onSubscribe: "</span>);</div><div class="line">        &#125;</div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onNext</span><span class="params">(String string)</span> </span>&#123;</div><div class="line">            Log.d(TAG, <span class="string">"onNext: "</span> + string);</div><div class="line">        &#125;</div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onError</span><span class="params">(Throwable e)</span> </span>&#123;</div><div class="line">            Log.d(TAG, <span class="string">"onError: "</span> + e.getMessage());</div><div class="line">        &#125;</div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onComplete</span><span class="params">()</span> </span>&#123;</div><div class="line">            Log.d(TAG, <span class="string">"onComplete: "</span>);</div><div class="line">        &#125;</div><div class="line">    &#125;;</div></pre></td></tr></table></figure>
</li>
<li><p>概念:</p>
<ol>
<li><p>订阅回调</p>
<ol>
<li><p>订阅回调指的是下游的on开头的方法都是回调方法，分别对应上游的方法进行回调。</p>
</li>
<li><p>如：</p>
<ol>
<li>上游的onNext()会回调下游的onNext()诸如此类。</li>
</ol>
</li>
</ol>
</li>
<li><p>一次性使用：</p>
<ol>
<li><p>Disposable：</p>
<ol>
<li><p>字面意思是单次使用，用完就销毁了。</p>
</li>
<li><p>我们可以将Disposable理解成拦河大坝。</p>
</li>
<li><p>当调用这个类的dispose()方式时，相当于将上下游的连接切断(相当于在小河上下游之间建起了拦河大坝，所有事件都无法流通到下游了)，此时会导致下游不再接收事件</p>
</li>
<li><p>但是上游将持续发送事件。</p>
</li>
<li><p>请看代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div></pre></td><td class="code"><pre><div class="line">Observable.create(<span class="keyword">new</span> ObservableOnSubscribe&lt;String&gt;() &#123;</div><div class="line">           <span class="meta">@Override</span></div><div class="line">           <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">subscribe</span><span class="params">(ObservableEmitter&lt;String&gt; e)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">               e.onNext(<span class="string">"事件0"</span>);</div><div class="line">               Log.d(TAG, <span class="string">"onNext0"</span>);</div><div class="line">               e.onNext(<span class="string">"事件1"</span>);</div><div class="line">               Log.d(TAG, <span class="string">"onNext1"</span>);</div><div class="line">               e.onNext(<span class="string">"事件2"</span>);</div><div class="line">               Log.d(TAG, <span class="string">"onNext2"</span>);</div><div class="line">               e.onNext(<span class="string">"事件3"</span>);</div><div class="line">               Log.d(TAG, <span class="string">"onNext3"</span>);</div><div class="line">               e.onNext(<span class="string">"事件4"</span>);</div><div class="line">               Log.d(TAG, <span class="string">"onNext4"</span>);</div><div class="line">               e.onComplete();</div><div class="line">               Log.d(TAG, <span class="string">"onComplete"</span>);</div><div class="line">           &#125;</div><div class="line">       &#125;).subscribe(<span class="keyword">new</span> Observer&lt;String&gt;() &#123;</div><div class="line">           Disposable mDisposable;</div><div class="line">           <span class="meta">@Override</span></div><div class="line">           <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onSubscribe</span><span class="params">(Disposable d)</span> </span>&#123;</div><div class="line">               mDisposable = d;  <span class="comment">//将Disposable提升为成员变量，便于在其他地方调用</span></div><div class="line">           &#125;</div><div class="line">           <span class="meta">@Override</span></div><div class="line">           <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onNext</span><span class="params">(String string)</span> </span>&#123;</div><div class="line">               Log.d(TAG, <span class="string">"onNext: "</span> + string);</div><div class="line">               <span class="keyword">if</span> (string.equals(<span class="string">"事件2"</span>)) &#123;</div><div class="line">                   mDisposable.dispose();</div><div class="line">                   Log.d(TAG, <span class="string">"切断水管"</span>);</div><div class="line">               &#125;</div><div class="line">           &#125;</div><div class="line">           <span class="meta">@Override</span></div><div class="line">           <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onError</span><span class="params">(Throwable e)</span> </span>&#123;</div><div class="line">               Log.d(TAG, <span class="string">"onError: "</span>);</div><div class="line">           &#125;</div><div class="line">           <span class="meta">@Override</span></div><div class="line">           <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onComplete</span><span class="params">()</span> </span>&#123;</div><div class="line">               Log.d(TAG, <span class="string">"onComplete: "</span>);</div><div class="line">           &#125;</div><div class="line">       &#125;);</div></pre></td></tr></table></figure>
</li>
</ol>
</li>
<li><p>Disposable容器：</p>
<ol>
<li><p>所谓容器就是可以存放Disposable对象的类。我们将Disposable对象存放到容器中就方便对这些拦河大坝统一管理，什么时候开闸发水、蓄水都能够统一到一起。</p>
</li>
<li><p>CompositeDisposable：</p>
<ol>
<li><p>如果有多个Disposable的时候，RxJava内置了容器，当我们得到一个Disposable的时候，加入到容器中：</p>
<pre><code>CompositeDisposable.add()
</code></pre></li>
<li><p>随后，退出的时候，直接使用下述代码就能切断所有联系：</p>
<pre><code>CompositeDisposable.clear()
</code></pre><ol>
<li>清除容器中所有的Disposable随想，同时截断所有河流。</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
<li><p>实现订阅（Subscribe）</p>
<ol>
<li><p>创建了Observable和Subscriber之后，使用一个方法将两者关联起来就是实现订阅了：</p>
<ol>
<li><p>实现订阅：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">subscribe()： <span class="comment">//实现订阅的API</span></div><div class="line">observable.subscribe(observer);</div></pre></td></tr></table></figure>
<ol>
<li>这个方法的调用，其实看起来像是被观察者订阅了观察者，感觉就像是“杂志订阅了读者”。但是如果不这样写，对流式Api的设计就会造成影响(也就是整个架构就得要重新设计，得不偿失)，因此才这么设计。</li>
</ol>
</li>
</ol>
</li>
<li><p>subscribe()方法的多个重载方法的分析（不完整订阅）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> Disposable <span class="title">subscribe</span><span class="params">()</span> </span>&#123;&#125;</div><div class="line"><span class="comment">//不论上游发射什么事件，我都不处理</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> Disposable <span class="title">subscribe</span><span class="params">(Consumer&lt;? <span class="keyword">super</span> T&gt; onNext)</span></span></div><div class="line"><span class="comment">//只处理上游发射过来的onNext()事件</span></div><div class="line"><span class="keyword">public</span> <span class="keyword">final</span> Disposable <span class="title">subscribe</span><span class="params">(Consumer&lt;? <span class="keyword">super</span> T&gt; onNext, Consumer&lt;? <span class="keyword">super</span> Throwable&gt; onError)</span></div><div class="line"><span class="comment">//只处理上游发射过来的onNext()、onError()事件</span></div><div class="line"><span class="keyword">public</span> <span class="keyword">final</span> Disposable <span class="title">subscribe</span><span class="params">(Consumer&lt;? <span class="keyword">super</span> T&gt; onNext, Consumer&lt;? <span class="keyword">super</span> Throwable&gt; onError, Action onComplete)</span></div><div class="line"><span class="comment">//只处理上游发射过来的onNext()、onError()、onComplete()事件</span></div><div class="line"><span class="keyword">public</span> <span class="keyword">final</span> Disposable <span class="title">subscribe</span><span class="params">(Consumer&lt;? <span class="keyword">super</span> T&gt; onNext, Consumer&lt;? <span class="keyword">super</span> Throwable&gt; onError, Action onComplete, Consumer&lt;? <span class="keyword">super</span> Disposable&gt; onSubscribe)</span></div><div class="line"><span class="comment">//只处理上游发射过来的onNext()、onError()、onComplete()、onSubscribe事件</span></div><div class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">subscribe</span><span class="params">(Observer&lt;? <span class="keyword">super</span> T&gt; observer)</span></div><div class="line"><span class="comment">//完整订阅</span></div></pre></td></tr></table></figure>
</li>
</ol>
</li>
</ol>
  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/categories/RXJava系列/">RXJava系列</a>
</div>


  <div class="article-tags">
  
  <span></span> <a href="/tags/RxJava/">RxJava</a><a href="/tags/RxJava基础/">RxJava基础</a><a href="/tags/观察者模式/">观察者模式</a>
  </div>

</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://www.ryanhuen.tech/2017/02/16/rx-serials-base-intro/" data-title="RxJava基础篇(一) | RyanHuen" data-tsina="null" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/2017/02/16/rx-thread-control/" title="RxJava基础篇(二):线程控制">
  <strong>上一篇：</strong><br/>
  <span>
  RxJava基础篇(二):线程控制</span>
</a>
</div>


<div class="next">
<a href="/2017/02/15/rx-serials-respon-explain/"  title="什么是响应式编程">
 <strong>下一篇：</strong><br/> 
 <span>什么是响应式编程
</span>
</a>
</div>

</nav>

	
<section id="comments" class="comment">
	<div class="ds-thread" data-thread-key="2017/02/16/rx-serials-base-intro/" data-title="RxJava基础篇(一)" data-url="http://www.ryanhuen.tech/2017/02/16/rx-serials-base-intro/"></div>
</section>


</div>  
      <div class="openaside"><a class="navbutton" href="#" title="显示侧边栏"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">文章目录</strong>
 
 <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#RxJava中有四个概念："><span class="toc-number">1.</span> <span class="toc-text">RxJava中有四个概念：</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#RxJava与传统观察者模式异同："><span class="toc-number">2.</span> <span class="toc-text">RxJava与传统观察者模式异同：</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Rx事件模型："><span class="toc-number">3.</span> <span class="toc-text">Rx事件模型：</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Rx事件模型图："><span class="toc-number">3.1.</span> <span class="toc-text">Rx事件模型图：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#首先了解几个概念："><span class="toc-number">3.2.</span> <span class="toc-text">首先了解几个概念：</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#基本使用："><span class="toc-number">4.</span> <span class="toc-text">基本使用：</span></a></li></ol>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="隐藏侧边栏"></a></div>
<aside class="clearfix">

  
<div class="categorieslist">
	<p class="asidetitle">分类</p>
		<ul>
		
		  
			<li><a href="/categories/Emacs系列/" title="Emacs系列">Emacs系列<sup>3</sup></a></li>
		  
		
		  
			<li><a href="/categories/Framework系列/" title="Framework系列">Framework系列<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/categories/RXJava系列/" title="RXJava系列">RXJava系列<sup>7</sup></a></li>
		  
		
		  
			<li><a href="/categories/git入门系列/" title="git入门系列">git入门系列<sup>5</sup></a></li>
		  
		
		  
			<li><a href="/categories/Emacs系列/org-mode/" title="org-mode">org-mode<sup>1</sup></a></li>
		  
		
		</ul>
</div>


  
<div class="tagslist">
	<p class="asidetitle">标签</p>
		<ul class="clearfix">
		
			
				<li><a href="/tags/RxJava/" title="RxJava">RxJava<sup>7</sup></a></li>
			
		
			
				<li><a href="/tags/git/" title="git">git<sup>5</sup></a></li>
			
		
			
				<li><a href="/tags/RxJava基础/" title="RxJava基础">RxJava基础<sup>4</sup></a></li>
			
		
			
				<li><a href="/tags/Spacemacs/" title="Spacemacs">Spacemacs<sup>3</sup></a></li>
			
		
			
				<li><a href="/tags/Emacs/" title="Emacs">Emacs<sup>3</sup></a></li>
			
		
			
				<li><a href="/tags/观察者模式/" title="观察者模式">观察者模式<sup>3</sup></a></li>
			
		
			
				<li><a href="/tags/BackPressure/" title="BackPressure">BackPressure<sup>1</sup></a></li>
			
		
			
				<li><a href="/tags/org/" title="org">org<sup>1</sup></a></li>
			
		
			
				<li><a href="/tags/Java回调/" title="Java回调">Java回调<sup>1</sup></a></li>
			
		
			
				<li><a href="/tags/Debug/" title="Debug">Debug<sup>1</sup></a></li>
			
		
			
				<li><a href="/tags/设计模式/" title="设计模式">设计模式<sup>1</sup></a></li>
			
		
			
				<li><a href="/tags/RxJava操作符/" title="RxJava操作符">RxJava操作符<sup>1</sup></a></li>
			
		
			
				<li><a href="/tags/响应式编程/" title="响应式编程">响应式编程<sup>1</sup></a></li>
			
		
			
				<li><a href="/tags/Android-Studio/" title="Android Studio">Android Studio<sup>1</sup></a></li>
			
		
			
				<li><a href="/tags/Framework/" title="Framework">Framework<sup>1</sup></a></li>
			
		
			
				<li><a href="/tags/org-mode/" title="org-mode">org-mode<sup>1</sup></a></li>
			
		
		</ul>
</div>


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS 订阅</a>
</div>

</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hi there,I&#39;m RyanHuen <br/>
			A simple programmer</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		<a href="http://weibo.com/ryanxuan" target="_blank" class="icon-weibo" title="微博"></a>
		
		
		<a href="https://github.com/RyanHuen" target="_blank" class="icon-github" title="github"></a>
		
		
		
		
		
		
		
		<a href="http://www.zhihu.com/people/ryan-hyn" target="_blank" class="icon-zhihu" title="知乎"></a>
		
		
		
		<a href="mailto:ryanhuenwork@163.com" target="_blank" class="icon-email" title="Email Me"></a>
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2017 
		
		<a href="/about" target="_blank" title="RyanHuen">RyanHuen</a>
		
		
		</p>
</div>
</footer>
    <script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/jquery.imagesloaded.min.js"></script>
<script src="/js/gallery.js"></script>
<script src="/js/jquery.qrcode-0.12.0.min.js"></script>

<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>



<script type="text/javascript">
  var duoshuoQuery = {short_name:"ryanhuen"};
  (function() {
    var ds = document.createElement('script');
    ds.type = 'text/javascript';ds.async = true;
    ds.src = '//static.duoshuo.com/embed.js';
    ds.charset = 'UTF-8';
    (document.getElementsByTagName('head')[0] 
    || document.getElementsByTagName('body')[0]).appendChild(ds);
  })();
</script> 







<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?af124d045b4aed59105f75db52359992";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="返回顶部"><img src="/img/scrollup.png"/></a>
	</div>
	<script src="/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
